import React from 'react';
import { Button, Form, Input, Select, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import axios from '../../API';
import '../../style/register.css';

const { Option } = Select;

const formItemLayout = {
  labelCol: { xs: { span: 24 }, sm: { span: 8 } },
  wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },
};

const tailFormItemLayout = {
  wrapperCol: { xs: { span: 24, offset: 0 }, sm: { span: 16, offset: 8 } },
};

const Register = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();

  const onFinish = async (values) => {
    console.log('提交的数据:', values);  // 打印提交的表单数据
    try {
      const response = await axios.post('/users/add', {
        email: values.email,
        password: values.password,
        nickname: values.nickname,
        phone: values.phone,
        gender: values.gender,  // 确保这里的 gender 是正确的
        age: values.age,
      });

      if (response.data.code === 200) {
        message.success('注册成功！正在跳转到登录页面...');
        navigate('/');
      } else {
        message.error(response.data.message || '注册失败，请重试！');
      }
    } catch (error) {
      if (error.response) {
        console.error('注册请求失败:', error.response.data);
        message.error(error.response.data.message || '发生错误，请稍后重试');
      } else if (error.request) {
        console.error('未收到响应:', error.request);
        message.error('网络错误，请检查连接');
      } else {
        console.error('请求配置错误:', error.message);
        message.error('请求配置错误');
      }
    }
  };



  return (
      <div className="site2">
        <div className="regis_container">
          <div className="regist">
            <div className="regileft">
              <h1>欢迎注册</h1>
              <h2>请填写您的信息</h2>
            </div>
            <div className="regimain">
              <Form
                  {...formItemLayout}
                  form={form}
                  name="register"
                  onFinish={onFinish}
                  style={{ maxWidth: 600 }}
                  scrollToFirstError
              >
                <Form.Item
                    name="email"
                    label="邮箱"
                    rules={[
                      { type: 'email', message: '邮箱格式不正确' },
                      { required: true, message: '请输入您的邮箱地址' },
                    ]}
                >
                  <Input />
                </Form.Item>

                <Form.Item
                    name="password"
                    label="密码"
                    rules={[{ required: true, message: '请输入密码' }]}
                    hasFeedback
                >
                  <Input.Password />
                </Form.Item>

                <Form.Item
                    name="confirm"
                    label="确认密码"
                    dependencies={['password']}
                    hasFeedback
                    rules={[
                      { required: true, message: '请再次输入密码' },
                      ({ getFieldValue }) => ({
                        validator(_, value) {
                          if (!value || getFieldValue('password') === value) {
                            return Promise.resolve();
                          }
                          return Promise.reject(new Error('两次输入的密码不一致'));
                        },
                      }),
                    ]}
                >
                  <Input.Password />
                </Form.Item>

                <Form.Item
                    name="nickname"
                    label="昵称"
                    rules={[{ required: true, message: '请输入您的昵称', whitespace: true }]}
                >
                  <Input />
                </Form.Item>

                <Form.Item
                    name="phone"
                    label="电话号码"
                    rules={[{ required: true, message: '请输入您的电话号码' }]}
                >
                  <Input
                      addonBefore={
                        <Select defaultValue="86" style={{ width: 70 }}>
                          <Option value="86">+86</Option>
                          <Option value="87">+87</Option>
                        </Select>
                      }
                      style={{ width: '100%' }}
                  />
                </Form.Item>

                <Form.Item
                    name="gender"
                    label="性别"
                    rules={[{ required: true, message: '请选择您的性别' }]}
                >
                  <Select>
                    <Option value="男">男</Option>
                    <Option value="女">女</Option>
                    <Option value="未知">未知</Option>
                  </Select>
                </Form.Item>

                <Form.Item
                    name="age"
                    label="年龄"
                    rules={[{ required: true, message: '请输入您的年龄' }]}
                >
                  <Input type="number" min={1} />
                </Form.Item>

                <Form.Item {...tailFormItemLayout}>
                  <Button type="primary" htmlType="submit" className="submit">
                    注册
                  </Button>
                </Form.Item>
              </Form>
            </div>
          </div>
        </div>
      </div>
  );
};

export default Register;
